import random
import string
from datetime import datetime, timedelta
from flask_mail import Message

class VerificationCodeManager:
    def __init__(self):
        self.codes = {}  # 格式: {email: (code, expiry, purpose)}
        
    def generate_code(self):
        """生成6位数字验证码"""
        return ''.join(random.choices(string.digits, k=6))
        
    def create_code(self, email, purpose, expire_minutes=5):
        """创建新的验证码"""
        code = self.generate_code()
        expiry = datetime.utcnow() + timedelta(minutes=expire_minutes)
        self.codes[email] = (code, expiry, purpose)
        return code, expiry
        
    def verify_code(self, email, code, purpose):
        """验证验证码"""
        if email not in self.codes:
            return False, "请先获取验证码"
            
        stored_code, expiry, stored_purpose = self.codes[email]
        if stored_code != code:
            return False, "验证码错误"
            
        if expiry < datetime.utcnow():
            del self.codes[email]
            return False, "验证码已过期"
            
        if stored_purpose != purpose:
            return False, "验证码用途不匹配"
            
        # 验证成功后删除
        del self.codes[email]
        return True, "验证成功"

class EmailService:
    def __init__(self, app, mail):
        self.app = app
        self.mail = mail
        
    def send_verification(self, email, code, purpose, expire_minutes=5):
        """发送验证码邮件"""
        subject = "验证码"
        if purpose == "register":
            subject = "注册验证码"
        elif purpose == "reset":
            subject = "密码重置验证码"
            
        body = f"您的{subject}是: {code}，有效期为{expire_minutes}分钟。"
        return self.send_email(email, subject, body)
        
    def send_alert(self, user_email, alert_info):
        """发送警报邮件"""
        subject = "设备警报通知"
        body = f"""
        设备ID: {alert_info['device_id']}
        警报类型: {alert_info['alert_type']}
        触发值: {alert_info['trigger_value']}
        时间: {alert_info['timestamp']}
        """
        return self.send_email(user_email, subject, body)
        
    def send_email(self, recipient, subject, body):
        """通用邮件发送方法"""
        try:
            msg = Message(subject, recipients=[recipient], body=body)
            self.mail.send(msg)
            return True, "邮件发送成功"
        except Exception as e:
            self.app.logger.error(f"发送邮件失败: {str(e)}")
            return False, str(e)

def send_verification_code(email_service, code_manager, email, purpose, expire_minutes=5):
    """统一的验证码发送函数"""
    code, expiry = code_manager.create_code(email, purpose, expire_minutes)
    success, message = email_service.send_verification(email, code, purpose, expire_minutes)
    if not success:
        raise Exception(message)
    return code, expiry

def verify_code(code_manager, email, code, purpose):
    """统一的验证码验证函数"""
    return code_manager.verify_code(email, code, purpose)

def send_alert_email(email_service, user_email, alert_info):
    """统一的警报邮件发送函数"""
    return email_service.send_alert(user_email, alert_info) 